package com.jiahao.material.controllers;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiahao.material.entity.*;

import com.jiahao.material.mapper.RoleMenuMapper;
import com.jiahao.material.mapper.RolePermissionMapper;
import com.jiahao.material.mapper.UserRoleMapper;
import com.jiahao.material.services.IRoleService;

import com.jiahao.material.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    /**
     * 添加角色
     * @param map
     * @return
     * @throws Exception
     */
    @PostMapping("/add")
    @Transactional
    public Result add(@RequestBody Map<String,Object> map) throws Exception{
        //先保存角色
        Role role = new Role();
        role.setName(map.get("name").toString());
        role.setCode(map.get("code").toString());
        role.setStatus("01");
        role.setDescription(map.get("description").toString());
        roleService.save(role);

        //设置权限
        List<String> permissions = (List<String>) map.get("permissions");
        RolePermission rolePermission = new RolePermission();
        rolePermission.setRid(role.getId());
        for (String permission : permissions) {
            rolePermission.setPid(permission);
            rolePermissionMapper.insert(rolePermission);
        }

        //设置菜单
        List<String> menus = (List<String>) map.get("menus");
        RoleMenu roleMenu = new RoleMenu();
        roleMenu.setRid(role.getId());
        for (String menu : menus) {
            roleMenu.setMid(menu);
            roleMenuMapper.insert(roleMenu);
        }

        return ResultUtil.success("添加角色成功!");
    }

    /**
     * 根据id获取角色
     * @param id
     * @return
     * @throws Exception
     */
    @GetMapping("/byId/{id}")
    public Result getById(@PathVariable String id) throws Exception{
        Role byId = roleService.getById(id);
        return ResultUtil.success("",byId);
    }

    /**
     * 分页查询角色
     * @param map
     * @return
     * @throws Exception
     */
    @PostMapping("/page")
    public Result getByPage(@RequestBody Map<String,Object> map) throws Exception{
        int pageSize = map.get("pageSize") == null ? 10 : Integer.parseInt(map.get("pageSize").toString());
        int currentPage = map.get("currentPage") == null ? 1 : Integer.parseInt(map.get("currentPage").toString());
        Page<Role> page = new Page<>(currentPage,pageSize);
        return ResultUtil.success("",roleService.getByPage(page,map));
    }

    /**
     * 获取所有角色
     * @return
     * @throws Exception
     */
    @GetMapping("/all")
    public Result getAll() throws Exception{
        return ResultUtil.success("",roleService.list());
    }

    /**
     * 角色更新
     * @param map
     * @return
     * @throws Exception
     */
    @PutMapping("/update")
    public Result update(@RequestBody Map<String,Object> map) throws Exception{
        //先更新角色
        Role role = new Role();
        role.setId(map.get("id").toString());
        role.setName(map.get("name").toString());
        role.setCode(map.get("code").toString());
        role.setStatus("01");
        role.setDescription(map.get("description").toString());
        roleService.updateById(role);

        //更新权限
            //先删除原有权限
        QueryWrapper<RolePermission> rolePermissionQueryWrapper = new QueryWrapper<>();
        rolePermissionQueryWrapper.eq("rid",role.getId());
        rolePermissionMapper.delete(rolePermissionQueryWrapper);
            //插入更新后的权限
        List<String> permissions = (List<String>) map.get("permissions");
        RolePermission rolePermission = new RolePermission();
        rolePermission.setRid(role.getId());
        for (String permission : permissions) {
            rolePermission.setPid(permission);
            rolePermissionMapper.insert(rolePermission);
        }

        //更新菜单
            //先删除原有的菜单
        QueryWrapper<RoleMenu> roleMenuWrapper = new QueryWrapper<>();
        roleMenuWrapper.eq("rid",role.getId());
        roleMenuMapper.delete(roleMenuWrapper);
            //插入更新后的菜单
        List<String> menus = (List<String>) map.get("menus");
        RoleMenu roleMenu = new RoleMenu();
        roleMenu.setRid(role.getId());
        for (String menu : menus) {
            roleMenu.setMid(menu);
            roleMenuMapper.insert(roleMenu);
        }
        return ResultUtil.success("更新角色成功!");
    }

    /**
     * 更新状态
     * @param map
     * @return
     * @throws Exception
     */
    @PutMapping("/status")
    public Result updateStatus(@RequestBody Map<String,Object> map) throws Exception{
        UpdateWrapper<Role> roleUpdateWrapper = new UpdateWrapper<>();
        roleUpdateWrapper.eq("id",map.get("id").toString()).set("status",map.get("status").toString());
        roleService.update(roleUpdateWrapper);
        return ResultUtil.success("更新状态成功!");
    }

    @PostMapping("/checkCode")
    public Result checkCode(@RequestBody Map<String,Object> map) throws Exception{
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.eq("code",map.get("code").toString());
        Role one = roleService.getOne(roleQueryWrapper);
        String e="0";
        if (one!=null)
            e = one.getId().equals(map.get("id").toString())?"0":"1";
        return ResultUtil.success(e);
    }

    /**
     * 删除角色
     * @param id
     * @return
     * @throws Exception
     */
    @DeleteMapping("/del/{id}")
    public Result delById(@PathVariable String id) throws Exception{
        //删除角色与权限的关系
        QueryWrapper<RolePermission> rolePermissionQueryWrapper = new QueryWrapper<>();
        rolePermissionQueryWrapper.eq("rid",id);
        rolePermissionMapper.delete(rolePermissionQueryWrapper);

        //删除角色与用户的关系
        QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
        userRoleQueryWrapper.eq("rid",id);
        userRoleMapper.delete(userRoleQueryWrapper);

        roleService.removeById(id);
        return ResultUtil.success("删除角色成功!");
    }

    /**
     * 批量删除角色
     * @param ids
     * @return
     * @throws Exception
     */
    @PostMapping("/dels")
    public Result delByIds(@RequestBody List<String> ids) throws Exception{

        //删除角色与权限的关系
        QueryWrapper<RolePermission> rolePermissionQueryWrapper = new QueryWrapper<>();
        rolePermissionQueryWrapper.in("rid",ids);
        rolePermissionMapper.delete(rolePermissionQueryWrapper);

        //删除角色与用户的关系
        QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
        userRoleQueryWrapper.in("rid",ids);
        userRoleMapper.delete(userRoleQueryWrapper);

        //删除角色与用户的关系
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.in("rid",ids);
        roleService.remove(roleQueryWrapper);
        return ResultUtil.success("删除角色成功!");
    }

}
